package com.example;

/**
 * @Author loubobooo
 * @Description #67. 二进制求和
 * @Date 2020/3/23
 */
public class AddBinary {

    /**
     * @Author loubobooo
     * @Description 给定两个二进制字符串，返回他们的和（用二进制表示）。
     *
     * 输入为非空字符串且只包含数字 1 和 0。
     *
     * 示例 1:
     *
     * 输入: a = "11", b = "1"
     * 输出: "100"
     * @Date 2020/3/23 11:12
     * @Param
     * @return
     **/
    public String addBinary(String a, String b) {
        if (a == null || a.length() == 0 || b == null || b.length() == 0) {
            return "";
        }
        int aLength = a.length();
        int bLength = b.length();
        // 对齐ab长度
        String temp = "";
        for (int i = 0; i < Math.abs(aLength - bLength); i++) {
            temp += "0";
        }
        if(aLength < bLength){
            a = temp + a;
        }else{
            b = temp + b;
        }
        StringBuilder strBuilder = new StringBuilder();
        // 利用保留余数
        int remainder = 0;
        for (int i = Math.max(aLength, bLength) - 1; i >= 0; i--) {
            int sum = remainder;
            // asci值运算
            sum = (a.charAt(i) - '0') + (b.charAt(i) - '0') + sum;
            strBuilder.append(sum % 2);
            remainder = sum / 2;
        }
        strBuilder.append(remainder == 1 ? "1" : "");
        return strBuilder.reverse().toString();
    }

    public static void main(String[] args) {
        AddBinary addBinary = new AddBinary();
        String s = addBinary.addBinary("1010", "1011");
        System.out.println(s);
    }


}
